I am new to flask and javascript, but I am making an app using flask, p5.js and the "onoff" javascript library for controlling GPIO pins. when I run the app without the onoff library it works fine, however after I add the onoff library I get the error "Uncaught ReferenceError: require is not defined". I tried running the javascript file directly from the terminal and from there it works fine and it just stops working when I run it in the browser with the flask app.
Right now, since I am only testing, the code is supposed to print in console when the GPIO detects a pulse, however my plan is to make it change the value of the variable "idx" and "idy" with each pulse so that I can change the position of the circle drawn.
here is my code:
var Gpio = require('onoff').Gpio; //include onoff to interact with the GPIO
const pinInput = new Gpio(4, 'in', 'both'); //use GPIO pin 17 as input, and 'both' button presses, and releases should be handled
const w = 672;
const h = 504;
let canvas;
let idx = 0;
let idy = 0;
let Xcoords = [150, 541, 149, 541];
let Ycoords = [168, 175, 375, 376];
function setup() {
canvas = createCanvas(w, h);
canvas.parent("canvasHolder");
noFill();
stroke(255, 204, 0);
strokeWeight(6);
}
function draw() {
ellipse(Xcoords[idx], Ycoords[idy], 40, 40);
}
pinInput.watch(function (err, value) { //Watch for hardware interrupts on pushButton GPIO, specify callback function
if (err) { //if an error
console.error('There was an error', err); //output error message to console
return;
}
console.log(value);
console.log("test print");
});
function unexportOnClose() { //function to run when exiting program
pinInput.unexport(); // Unexport Button GPIO to free resources
};
process.on('SIGINT', unexportOnClose); //function to run when user closes using ctrl+c
}
if you need more information regarding my code please let me know.
The APIs you are using depend on Node.js. They will not run in the browser.
(The specific error you are encountering is because require is part of the CommonJS module specification as implemented by Node.js but browsers don't support that).
It would be very dangerous if a malicious developer could tells any of their visitors' browsers to interact in arbitrary ways with the GIPO pins on their computers!
If you want to interact with them from a browser, then you need to do so using a web service.
You could write such a service using JavaScript running on Node.js, but since you already have Flask on the server side, it would make more sense to use the Python equivalent.